<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div>
        <div style="display: flex;line-height: 60px;">
            <div style="margin-top: 8px;">
                <component class="icons" :is="props.icon" @click="doCollaspe"></component>
            </div>
            <div style="flex:1;text-align: center;font-size: 24px;">
                <span>admin管理系统</span>
            </div>
            <div style="margin-top: 5px;margin-left: 50px;">
                <el-avatar :size="50" :src="user.avatar">
                </el-avatar>

            </div>
            <el-dropdown style="margin-left: 15px;margin-top: 20px;">
                <el-button type="primary">
                    {{ roleLabel }} [{{ user.username }}]
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="toIndex">系统首页</el-dropdown-item>
                        <el-dropdown-item @click="toUser">个人中心</el-dropdown-item>
                        <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                        <el-dropdown-item @click="delUser">注销用户</el-dropdown-item>
                    </el-dropdown-menu>
                </template>

            </el-dropdown>
            <div style="margin-top: 5px; margin-left: 5px">
                <el-button type="primary" style="font-size:20px" @click="drawer = true"><el-icon>
                        <Setting />
                    </el-icon></el-button>

            </div>
        </div>
        <el-drawer v-model="drawer" direction="rtl" size="25%">
            <el-card shadow="hover" class="box-card centered-card blue" :show-close="false">
                <div>
                    <el-avatar size="large" :src="user.avatar" fit="cover"
                        style="width: 100px;height: 100px;"></el-avatar>
                </div>
                <el-button type="success" size="small" @click="modAvatar">更换头像</el-button>
            </el-card>
            <el-col :span="24">
                <el-card shadow="hover" class="box-card centered-card pink">
                    <div>
                        <el-button type="success" @click="dialogNameVisible = true">修改昵称</el-button>
                    </div>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card green">
                    <div>
                        <el-button type="primary" @click="dialogPwdVisible = true">
                            修改密码</el-button>
                    </div>
                </el-card>
            

                <el-card shadow="hover" class="box-card centered-card orange">
                    <div>
                        <el-button type="danger" @click="logout">退出登录</el-button>
                    </div>
                </el-card>
                <el-card shadow="hover" class="box-card centered-card red">
                    <div>
                        <el-button type="danger" @click="delUser">注销账号</el-button>
                    </div>
                </el-card>
            </el-col>
        </el-drawer>
        <el-dialog title="修改昵称" v-model="dialogNameVisible" width="30%" center>
            <el-form :model="modNameForm" label-width="100px" :rules="namerules" ref="modNameFormRef">
                <el-form-item label="账号昵称">
                    <el-input style="width: 200px" type="text" :placeholder="user.name" size="small"
                        disabled></el-input>
                </el-form-item>
                <el-form-item label="新昵称" prop="name">
                    <el-input style="width: 200px" type="text" v-model="modNameForm.name" autocomplete="off"
                        size="small" @keyup.enter="modName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>

                <el-button type="danger" @click="dialogNameVisible = false">取消修改</el-button>
                <el-button type="success" @click="modName">开始修改</el-button>
            </template>
        </el-dialog>
        <el-dialog title="修改密码" v-model="dialogPwdVisible" width="30%" center>
            <el-form :model="modPwdForm" label-width="100px" :rules="rules" ref="modPwdFormRef">
                <el-form-item label="原密码" prop="password">
                    <el-input style="width: 200px" type="text" v-model="modPwdForm.password" show-password
                        autocomplete="off" size="small"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newpassword">
                    <el-input style="width: 200px" type="password" v-model="modPwdForm.newpassword" show-password
                        autocomplete="off" size="small"></el-input>
                </el-form-item>
                <el-form-item label="重复密码" prop="rpassword">
                    <el-input style="width: 200px" type="password" v-model="modPwdForm.rpassword" show-password
                        autocomplete="off" size="small" @keyup.enter="modPwd"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="danger" @click="dialogPwdVisible = false">取消修改</el-button>
                <el-button type="success" @click="modPwd">开始修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, computed,onMounted, reactive, defineProps, defineEmits } from 'vue'
import api from '../axios/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Store } from '@/store/index'
import mitting from '@/assets/mitting'
// 获取 store 实例
const store = Store()
const router = useRouter()
const user =JSON.parse(localStorage.getItem('CurUser')) 
// props 和 emit
const props = defineProps(['icon'])
const emit = defineEmits(['doCollaspe'])
const doCollaspe = () => {
    console.log('doCollaspe')
    emit('doCollaspe')
}
const drawer = ref(false)
let dialogNameVisible = ref(false)
let dialogPwdVisible = ref(false)
// 表单数据
const modNameForm = reactive({ name: '' })
const modPwdForm = reactive({ password: '', newpassword: '', rpassword: '' })

// 昵称规则
const namerules = {
    name: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 2, max: 10, message: '2-10个字符', trigger: 'blur' }
    ]
}

// 密码规则
const rules = {
    password: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 6, max: 16, message: '6-16个字符', trigger: 'blur' }
    ],
    newpassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 16, message: '6-16个字符', trigger: 'blur' }
    ],
    rpassword: [
        { required: true, validator: validatePass, trigger: 'blur' },
        { min: 6, max: 16, message: '6-16个字符', trigger: 'blur' }
    ]
}

function validatePass(rule, value, callback) {
    if (!value) {
        callback(new Error('请再次输入密码'))
    } else if (value !== modPwdForm.newpassword) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}
const roleData = ref([])
function loadRole() {
    api.post("/role/listPage", {
        pageSize: 1000,
        pageNum: 1,
        param: {
        }
    }).then((res) => {
        if (res.code == 200) {
            roleData.value = res.data

        } else {
            ElMessage({
                message: '数据查询失败',
                type: "error"
            })
        }
    })
}
// 角色标签计算属性
const roleLabel = computed(() => {
  return roleData.value.find(item => item.id == user.role)?.name || '未知角色'
})
const modNameFormRef = ref(null)
const modPwdFormRef = ref(null)

const toUser = () => router.push('/Setting')

const toIndex = () => router.push('/Home')


const modAvatar = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = async () => {
        const file = input.files[0]
        if (file) {
            try {
                const fd = new FormData()
                fd.append('file', file)
                fd.append('name', file.name)

                const res = await api.post('/file/upload', fd)
                console.log(res)
                if (res.code === 200) {
                    await modUserAvatar(res.data.url)
                    ElMessage.success('上传成功！')
                } else {
                    ElMessage.error('未上传成功！')
                }
            } catch (err) {
                ElMessage.error('请求失败：' + err)
            }
        } else {
            ElMessage.error('未选择文件')
        }
    }
    input.click()
}

const modUserAvatar = async (avatar) => {
console.log(avatar)
    const res = await api.get(`/user/modAvatar?id=${user.id}&avatar=${avatar}`)
    if (res.code === 200) {
        getUserById()
    }
}

const getUserById = async () => {
    const res = await api.get(`/user/info/${user.id}`)
    if (res.code === 200) {
        console.log(res.data)
        store.setUser(res.data)
        user.value = res.data
    }
}

const modName = () => {
    modNameFormRef.value.validate(valid => {
        if (valid) {
            api.get(`/user/modName?id=${user.id}&name=${modNameForm.name}`)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('修改成功')
                        dialogNameVisible = false
                        getUserById()
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
        } else {
            ElMessage.warning('新账号昵称不符合规范')
            return false
        }
    })
}
const modPwd = () => {
    modPwdFormRef.value.validate(valid => {
        if (valid) {
            api.get(`/user/modPwd?id=${user.id}&password=${modPwdForm.newpassword}`)
                .then(res=> {
                    if (res.code === 200) {
                       logout()
                    } else {
                        ElMessage.error('修改失败')
                    }
                })
        } else {
            ElMessage.warning('请检查密码')
            return false
        }
    })
}

const logout = () => {
    console.log(user)
    api.get(`/user/logout/${user.id}`).then(res  => {
        if (res.code === 200) {
            ElMessage.success('退出登录成功')
            router.push('/Login')
            store.resetStatus()
        } else {
            ElMessage.error('退出登录失败，请稍后再试！')
        }
    })
}
const delUser = () => {
    ElMessageBox.confirm('您确定要注销用户吗？一旦注销，您将再也无法进入系统', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
    }).then(() => {
        api.get(`/user/delUser/${user.id}`).then(res  => {
            if (res.code === 200) {
                ElMessage.success('注销用户成功')
                router.push('/')
                store.resetStatus()
            } else {
                ElMessage.error('注销用户失败，请稍后再试！')
            }
        })
    }).catch(() => {
        ElMessage.info('已取消注销用户')
    })
}
onMounted(() => { 
    loadRole()
    mitting.on('update-user',getUserById)
    // console.log(user)
})
</script>
<style scoped>
.icons {
    width: 25px;
    height: 25px;
}

  .box-card {
    height: auto;
    min-height: 50px;
    text-align: center;
    border-radius: 25px;
    margin: 10px;
  }
  
  .card-row {
    display: flex;
    justify-content: center;
  }
  
  .centered-card {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .red {
    background-color: rgb(231, 9, 9);
  }
  
  .green {
    background-color: rgb(152, 246, 11);
  }
  
  .purple {
    background-color: rgb(135, 53, 212);
  }
  
  .blue {
    background-color: rgb(10, 138, 207);
  }
  
  .orange {
    background-color: chocolate;
  }
  
  .grey {
    background-color: grey;
  }
  
  .pink {
    background-color: pink;
  }
  
  .gold {
    background-color: goldenrod;
  }
  </style>